using Admin2025.Application.Events;
using MediatR;
using Microsoft.Extensions.Logging;

namespace Admin2025.Application.EventHandlers;

/// <summary>
/// 用户创建事件处理器 - 发送欢迎邮件
/// </summary>
public class UserCreatedWelcomeHandler : INotificationHandler<UserCreatedNotification>
{
    private readonly ILogger<UserCreatedWelcomeHandler> _logger;

    public UserCreatedWelcomeHandler(ILogger<UserCreatedWelcomeHandler> logger)
    {
        _logger = logger;
    }

    public async Task Handle(UserCreatedNotification notification, CancellationToken cancellationToken)
    {
        var userEvent = notification.UserCreatedEvent;
        
        _logger.LogInformation("开始发送欢迎邮件: 事件ID={EventId}, 用户ID={UserId}, 用户名={Username}", 
            userEvent.EventId, userEvent.UserId, userEvent.Username);

        try
        {
            // 模拟发送欢迎邮件
            await SendWelcomeEmail(userEvent.Username);
            
            _logger.LogInformation("欢迎邮件发送成功: 用户ID={UserId}", userEvent.UserId);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "欢迎邮件发送失败: 用户ID={UserId}", userEvent.UserId);
        }
    }

    private async Task SendWelcomeEmail(string username)
    {
        // 模拟发送邮件的异步操作
        await Task.Delay(100);
        _logger.LogInformation("欢迎邮件已发送给用户: {Username}", username);
    }
}
